package com.sky.controller.admin;


import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
public class CommonController {


    @Autowired
    private AliOssUtil aliOssUtil;


    /*
    * 文件上传
    * */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) throws FileNotFoundException {
        log.info("文件上传：{}",file.getOriginalFilename());
        // 1.获取图片文件扩展名
        String originalFilename = file.getOriginalFilename();
        String subName="";
        if (originalFilename == null) {
            throw new FileNotFoundException();
        }
            // 获取文件后缀名
        subName = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成随机的uuid名的图片
        String prefix = UUID.randomUUID().toString();
        String fileName=prefix+subName;
        // 2.上传文件
        try {
            String uploaded = aliOssUtil.upload(file.getBytes(), fileName);
            log.info("文件上传成功！url:"+uploaded);
            // 返回文件url
            return Result.success(uploaded);
        } catch (IOException e) {
            log.error("文件上传失败！！");
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

}
